package com.qf.mybatis925.service.impl;

import com.qf.mybatis925.entity.LoginUser;
import com.qf.mybatis925.entity.User;
import com.qf.mybatis925.entity.UserDTO;
import com.qf.mybatis925.mapper.UserMapper;
import com.qf.mybatis925.service.UserService;
import com.qf.mybatis925.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(LoginUser loginUser) {
        try {
            Authentication authenticate = authenticationManager.
                    authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword()));

            HashMap<String, Object> map = new HashMap<>();
            map.put("username", authenticate.getName());
            map.put("perms", authenticate.getAuthorities());
            return jwtUtils.createToken(map);
        } catch (Exception e) {
            System.err.println("登录失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("用户名或密码错误");
        }
    }

    @Override
    public List<User> list(UserDTO userDTO) {
        return userMapper.list(userDTO);

    }

    @Override
    public int batchDelete(List<Integer> ids) {
        return userMapper.batchDelete(ids);
    }

    @Override
    public void add(User user) {
        System.out.println("注册用户:" + user);
        // 密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(user.getPassword());
        System.out.println("加密后密码 = " + encode);
        user.setPassword(encode);

        // 使用注入的mapper实例调用save方法
        userMapper.save(user);  // 修改此处
}


    @Override
    public int update(User user) {
        return userMapper.update(user);
    }
}
